package fans_group

import (
	"encoding/json"
	"github.com/spf13/cast"
	"longmen/server/config/global"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"strconv"
)

const (
	C2CFansGroupHistory = "fans_history" // 粉丝群聊天记录
)

type GetChatHistoryRequest struct {
	TypeName string `json:"type"`
	GroupId  string `json:"group_id"`
	Page     int    `json:"page"`
	Limit    int    `json:"limit"`
}

func GetHistory(groupID []string, page, limit int, delStamp int64) ([]FansGroupHistory, int64) {
	return FansGroupHistory{}.getHistory(groupID, page, limit, delStamp)
}

func QueryByUserHistory(groupId string, userId, page, limit int) ([]FansGroupHistory, int64) {
	//查询当前用户清空消息的记录
	delStamp := int64(0)
	gcDel, err := db_main.GetGroupChatDelete(map[string]interface{}{
		"fans_group_id": groupId,
		"user_id":       userId,
	})
	if err != nil {
		global.Log.Error(err)
	}
	if gcDel.Id > 0 {
		delStamp = gcDel.CreateStamp
	}

	//清空未读消息计数
	defer cache.ResetGroupMsgUserRead(strconv.Itoa(userId), groupId)

	return GetHistory([]string{groupId}, page, limit, delStamp)
}

func bindChatHistory(pbReq *pb.CallbackReq, rawByte []byte) ([]FansGroupHistory, int64) {
	req := GetChatHistoryRequest{}
	err := json.Unmarshal(rawByte, &req)
	if err != nil {
		return nil, 0
	}
	return QueryByUserHistory(pbReq.GroupId, cast.ToInt(pbReq.From_Account), req.Page, req.Limit)

}
